﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Wheel : CombinableItem
{
    WheelJoint2D joint;
    Rigidbody2D thisRigid;
    Vector3 localAnchorPosition;
    public WheelField NewSetting;
  //  public JointMotor2D DownWheelMotor;
 //   private JointMotor2D JointMotor;
    public override ItemField ItemFieldSetting { get =>NewSetting; set => NewSetting  = value as WheelField ; }

    public override void DownloadInstanceField(object args)
    {
        base.DownloadInstanceField(args);
    //    JointMotor = this.transform.Find("Collider").GetComponentInChildren<WheelJoint2D>().motor;
      var tp = args as WheelField;
   //   DownWheelMotor = tp.Motor;
        this.transform.Find("Collider").GetComponentInChildren<WheelJoint2D>().motor = tp.Motor;
      //  JointMotor = tp.Motor;//DownWheelMotor;
    //    this.transform.Find("Collider").GetComponentInChildren<WheelJoint2D>().motor = JointMotor;

    }
    public override ItemField UploadInstanceField()
    {
        ItemFieldSetting = base.UploadInstanceField();
       // DownWheelMotor = this.transform.Find("Collider").GetComponentInChildren<WheelJoint2D>().motor.motorSpeed;
       (ItemFieldSetting as WheelField).Motor = this.transform.Find("Collider").GetComponentInChildren<WheelJoint2D>().motor;
        return ItemFieldSetting;

    }

    public override float SetRigidInfo(Rigidbody2D rigid)
    {
        var mass=
        base.SetRigidInfo(rigid);
        joint = this.transform.Find("Collider").GetComponentInChildren<WheelJoint2D>();
        this.transform.Find("Collider").GetComponentInChildren<WheelJoint2D>().connectedBody = rigid;
        joint.connectedAnchor = rigid.transform.InverseTransformPoint(joint.transform.TransformPoint(joint.anchor));
        localAnchorPosition = this.transform.InverseTransformPoint(joint.transform.TransformPoint(joint.anchor));
        return mass;
    }
    public override float RotationInDegree { get => base.RotationInDegree; set
        {
            if (joint != null && this.GetComponentInParent<Rigidbody2D>())
            {
                joint.connectedAnchor = this.GetComponentInParent<Rigidbody2D>().transform.InverseTransformPoint(this.transform.TransformPoint(localAnchorPosition));
            }
            base.RotationInDegree = value;
        }
    }

}
[System.Serializable]
public class WheelField : CombinableItemField
{
    public JointMotor2D Motor;
    public override void ClearWhenToBench()
    {
        base.ClearWhenToBench();
        Motor.motorSpeed = 0;
    }
}
